package xyz.jcat.sca.example.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class BlackListFilter implements GlobalFilter, Ordered {

    //模拟黑名单
    private static final List<String> BLACK_LIST = new ArrayList<>();

    static {
        BLACK_LIST.add("192.168.125.128");
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String requestIp = request.getRemoteAddress().getHostString();
        log.info("request ip => {}", requestIp);
        if(!BLACK_LIST.contains(requestIp)) {
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        String data = "Request be denied!";
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 过滤器执行优先级
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
